// pages/applyElectronicCard/applyElectronicCard.js
var app = getApp();
var animation
var provinceid = '';
var cityid = '';
var switchs = 1; //开关
var areaInfoName = []; //选中地区名称
var areaIdInfo = []; //选中的地区id信息

var countdown = 120;
var reget = '获取验证码';
var settime = function (that) {
  if (countdown == 0) {
    that.setData({
      is_show: true
    })
    countdown = 120;
    reget = '重新获取';
    return;
  } else {
    that.setData({
      is_show: false,
      last_time: countdown
    })
    countdown--;
    reget = '重新获取';
  }
  setTimeout(function () {
    settime(that)
  }, 1000)
}
Page({
  /**
   * 页面的初始数据
   * province_s:所有省份
   * city_s选择省对应的所有市,
   * area_s选择市对应的所有区
   * 
   */
  data: {
    sexType: 3,//1男 2女 3保密 
    animationAddressMenu: {},//地址选择
    addressMenuIsShow: false,
    value_sel: [0, 0, 0], //对应数组下标
    province_s: [],
    city_s: [],
    area_s: [],
    areaInfo_name: [], //选中地区名称

    village_name: '',//选中的园区信息
    village_id: '',//当前选中的id
    phone: '',//用户手机号码(提交的手机号码)
    oldPhone: '',//原来手机号码
    is_show: true, //是否显示倒计时
    showCode: false,
    getOnecode: reget, //内容
    last_time: '', //剩余时间
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 初始化动画变量
    var that = this;
    var animation = wx.createAnimation({
      duration: 500,
      transformOrigin: "50% 50%",
      timingFunction: 'ease',
    })
    that.animation = animation;
    that.getProvince(); //获取省份信息
    areaInfoName = [];
    areaIdInfo = [];
    switchs = 1;

  },
  //获取用户信息
  getUser() {
    var that = this;
    app.ajax({
      url: "User/User/getUser",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          wx.setStorageSync('phone', res.data.data.phone);
          wx.setStorageSync('user_id', res.data.data.user_id)
          that.setData({
            oldPhone: res.data.data.phone,
            phone: res.data.data.phone,
            showCode: res.data.data.phone?false:true,
          })
        } else {
          wx.setStorageSync('token', '');
          //app.showModal('', res.data.message);return;
        }
      }
    })
  },
  //取消更换手机号码
  clearChange(){
    this.setData({
      phone:this.data.oldPhone,
      showCode:false,
    })
  },
  //点击开始修修改手机号码
  changePhone() {
    var that = this;
    wx.showModal({
      title: '是否确认修改手机号码?',
      content: '修改手机号码需收验证码',
      confirmColor: '#4EB7FF',
      cancelColor: '#C4C4C4',
      success(res) {
        if (res.confirm) {
          that.setData({
            phone: '',
            showCode: true,
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  isPoneAvailable(str) {
    var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
    if (!myreg.test(str)) {
      return false;
    } else {
      return true;
    }
  },
  /*** 发送验证码*/
  sendCode() {
    var that = this;
    if (that.data.phone == '') {
      app.showToast('手机号码不能为空');
      return false;
    }
    if (!that.isPoneAvailable(that.data.phone)) {
      app.showToast('手机号码格式不正确');
      return false;
    }
    if (that.data.phone == that.data.oldPhone) {
      app.showToast('与原来号码一致');
      return false;
    }
    app.ajax({
      url: 'User/Login/send_sms',
      data: {
        phone: that.data.phone,
      },
      success: function (res) {
        that.setData({
          is_show: (!that.data.is_show) //false
        })
        settime(that); //刷新倒计时 
        that.setData({
          getOnecode: reget
        })
        app.showToast(res.data.message, "none", 2500, function () {});
      }

    })

  },
  //输入电话号码
  inputPhone(e) {
    console.log('电话号码', e.detail.value, this.data.oldPhone);
    var that = this;
    if (e.detail.value == that.data.oldPhone && that.data.oldPhone) {
      app.showToast('与原来号码一致');
      that.setData({showCode:false})
    }
    that.setData({
      phone: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getUser();
  },
  //输入园区名称监听
  villageName: function (event) {
    var that = this;
    if (event.detail.value == '') {
      that.setData({
        showpop: false
      })
    }
    that.setData({
      village_name: event.detail.value
    })
    that.getVillageMsg();
  },
  //获取园区名称
  getVillageMsg: function () {
    var that = this;
    if (areaInfoName.length == 0 || areaIdInfo.length == 0) {
      //app.showModal('请先确定位置信息', '', function () { });
      app.showToast("请先确定位置信息", "none", 2000, function () {});
    } else if (that.data.village_name == '') {
      app.showToast("园区名称不能为空", "none", 2000, function () {});
      //app.showModal('园区名称不能为空', '', function () { });
    } else {
      //发起ajax请求
      that.searchVillage();
    }

  },
  //获取性别
  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value,
    })
  },

  // 点击所在地区弹出选择框
  selectDistrict: function (e) {
    var that = this
    if (that.data.addressMenuIsShow) {
      return
    }
    that.startAddressAnimation(true)
  },
  // 执行动画
  startAddressAnimation: function (isShow) {
    //console.log(isShow)
    var that = this
    if (isShow) {
      that.animation.translateY(0 + 'vh').step()
    } else {
      that.animation.translateY(40 + 'vh').step()
    }
    that.setData({
      animationAddressMenu: that.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  // 点击地区选择取消按钮
  cityCancel: function (e) {
    this.startAddressAnimation(false)
  },
  // 点击地区选择确定按钮
  citySure: function (e) {
    var that = this;
    var value_sel = that.data.value_sel;
    that.startAddressAnimation(false)
    // 将选择的城市信息放入数组后期方便操作
    var areaInfo_name = []; //区域名称
    areaInfo_name.push(that.data.province_s[value_sel[0]].name);
    areaInfo_name.push(that.data.city_s[value_sel[1]].name);
    areaInfo_name.push(that.data.area_s[value_sel[2]].name);
    var area_id_Info = []; //区域id
    area_id_Info.push(that.data.province_s[value_sel[0]].id);
    area_id_Info.push(that.data.city_s[value_sel[1]].id);
    area_id_Info.push(that.data.area_s[value_sel[2]].id);
    areaInfoName = areaInfo_name;
    areaIdInfo = area_id_Info;
    console.log('选中的信息', areaInfo_name, areaIdInfo)
    areaInfo_name
    that.setData({
      areaInfo_name,
      // area_id_Info,
      areaName: that.data.area_s[value_sel[2]].name
    })
  },
  //点击黑色区域关闭地址选择
  hideCitySelected: function (e) {
    this.startAddressAnimation(false)
  },

  // 处理省市县联动逻辑
  cityChange: function (e) {
    var that = this;
    var value_sel = e.detail.value; //获取选中的id数组
    var provinces = this.data.provinces
    var citys = this.data.citys
    var areas = this.data.areas
    var province_Num = value_sel[0]
    var city_Num = value_sel[1]
    var county_Num = value_sel[2]
    //判断是否需要切换市区级
    if (this.data.value_sel[0] != province_Num) {
      var provinceid = that.data.province_s[province_Num].id; //获取省id查询市级信息
      that.getCity(provinceid); //获取市级信息
      this.setData({
        value_sel: [province_Num, 0, 0],
        village_name: '',
        village_id: ''
      })
    } else if (this.data.value_sel[1] != city_Num) { //判断是否需要切换区域
      var cityid = that.data.city_s[city_Num].id;
      that.getArea(cityid); //获取区域信息
      this.setData({
        value_sel: [province_Num, city_Num, 0],
        village_name: '',
        village_id: ''
      })
    } else {
      this.setData({
        value_sel: [province_Num, city_Num, county_Num],
        village_name: '',
        village_id: ''
      })
    }
  },

  //获取省级信息 getProvince
  getProvince: function () {
    var that = this;
    app.ajax({
      url: 'Common/Common/getProvince',
      method: "POST",
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            province_s: res.data.data
          })
          //初次进入才会调用 获取市区级
          if (that.data.city_s.length == 0) {
            that.getCity(res.data.data[0].id);
          }
        } else {
          app.showToast(res.data.message, "none", 2000, function () {});
        }
      }
    })
  },
  //获取市信息 getCity
  getCity: function (provinceid) {
    var that = this;
    app.ajax({
      url: 'Common/Common/getCity',
      method: "POST",
      data: {
        id: provinceid
      },
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            city_s: res.data.data
          });
          //重置区域信息 
          that.getArea(res.data.data[0].id);
        } else {
          app.showToast(res.data.message, "none", 2000, function () {});
        }
      }
    })
  },
  //获取区域信息 getArea
  getArea: function (cityid) {
    var that = this;
    app.ajax({
      url: 'Common/Common/getArea',
      method: "POST",
      data: {
        id: cityid
      },
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            area_s: res.data.data
          })
        } else {
          app.showToast(res.data.message, "none", 2000, function () {});
        }
      }
    })
  },
  // .............................地址选择end
  //from表单提交事件
  formbindSubmit: function (e) {
    var that = this;
    var formVal = e.detail.value;
    var p_id = areaIdInfo[0];
    var c_id = areaIdInfo[1];
    var a_id = areaIdInfo[2];
    console.log('form发生了submit事件，携带数据为：', formVal)
    console.log('地址信息', areaIdInfo)
  
     if (formVal.full_name == '') {
       app.showToast("姓名不能为空", "none", 2000, function () { }); return false
    }
     if (formVal.tel == '') {
       app.showToast("手机号不能为空", "none", 2000, function () { }); return false
    }
    if (areaInfoName.length <= 0 || areaIdInfo.length <= 0) {
      app.showToast("请先确定位置信息", "none", 2000, function () { }); return false
    }
    if (formVal.village_name == '' && that.data.village_id === "") {
      app.showToast("请选择园区", "none", 2000, function () { }); return false
    } 
    if (formVal.code == '' && formVal.phone != that.data.oldPhone) {
      app.showToast("验证码不能为空", "none", 2000, function () { }); return false
    } else {
      if (switchs == 0) { //开关
        return false;
      }
      switchs = 0;
      app.ajax({
        url: 'User/WaterCard/electronicWaterCardApplication',
        method: "POST",
        data: {
          province: p_id,
          city: c_id,
          area: a_id,
          village_name: that.data.village_name,
          village_id: that.data.village_id,
          full_name: formVal.name,
          sex: that.data.sexType,
          tel: formVal.phone,
          paper_type: 1,
          IDcard: formVal.papers,
          code: formVal.code
        },
        success: function (res) {
          if (res.data.code == 1000) {
            app.showToast(res.data.message, "none", 2000, function () {});
            setTimeout(() => {
              wx.navigateBack({
                delta: 1
              });
              switchs = 1;
            }, 2000);
          } else {
            app.showToast(res.data.message, "none", 2000, function () {
              switchs = 1;
            });

          }
          setTimeout(() => {
            switchs = 1;
          }, 3000);
        }
      })
    }
  },
  //选择性别
  chooseSex(e) {
    var { sex } = e.currentTarget.dataset;
    this.setData({
      sexType: sex
    })
  },
  //去查询
  gotoPark() {
    console.log('options.area0', areaIdInfo)
    if (areaIdInfo.length <= 0 || areaInfoName.length <= 0) {
      app.showToast('请先选择位置');
      return false;
    }
    wx.navigateTo({
      url: '../searchPark/searchPark?area0=' + areaIdInfo[0] + '&area1=' + areaIdInfo[1] + '&area2=' + areaIdInfo[2],
    })
  },
})